package Network;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashSet;
import java.util.Scanner;

public class TCPEchoServer {
    private  ServerSocket serverSocket = null;

    public TCPEchoServer(int port) throws IOException {
        serverSocket = new ServerSocket(port);
    }
    public  void start() throws IOException {
        System.out.println("服务器启动！！！");
        while(true) {
            Socket clientSocket = serverSocket.accept();
            processConnection(clientSocket);
        }
    }

    private static void processConnection(Socket clientSocket) throws IOException {
        //1. 打印日志 告知客户端这边已经连接上了
        System.out.printf("[%s:%d] 客户端上线 \n" ,clientSocket.getInetAddress(),clientSocket.getPort());
        //2.从socket 中获取流对象 因为Tcp是以流对象传输
        try(InputStream inputStream = clientSocket.getInputStream() ;
            OutputStream outputStream = clientSocket.getOutputStream()) {

            //3. 创建一个循环  针对多个请求 客户端可能会发多个请求 所以也要去接收
            Scanner scanner = new Scanner(inputStream);
            while(true) {

                //3.1 接收请求并解析
                //3.1.1 先判断是否传输到服务器没
                if(!scanner.hasNext()) {
                    System.out.printf("[%s:%d] 客户端下线！\n",clientSocket.getInetAddress(),clientSocket.getPort());
                    break;
                }
                String request = scanner.next();
                //3.2 根据请求计算响应
                String response = process(request);
                //3.3 将响应发送给客户端
                outputStream.write(response.getBytes(),0,response.getBytes().length);
                //3.4 打印日志
                System.out.printf("[%s:%d] req=%s,resp=%s\n",clientSocket.getInetAddress(),clientSocket.getPort()
                 ,request,response);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            clientSocket.close();
        }

    }

    private static String process(String request) {
        return request+"\n";
    }

    public static void main(String[] args) throws IOException {
        TCPEchoServer server = new TCPEchoServer(9090);
        //server.start();
      String s = "hh";
        System.out.println(s.charAt(1));


    }


}
